﻿
using RFIDData.Data;
using RFIDData.Models;
using StudyKitLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Phoenix_RFID
{
    public partial class CardRegister : Form
    {
        Dbman dm = new Dbman();
        RFIDDB context = new RFIDDB();
        public CardRegister()
        {
            InitializeComponent();
            RFIDDB context = new RFIDDB();
            foreach (var kk in context.Employees)
            {
                cboEmployeeNo.Items.Add(kk.EmNo);
            }
            if (cboEmployeeNo.Items.Count > 0)
            {
                cboEmployeeNo.SelectedIndex = 0;

            }


            try
            {
                for (int port = 1; port < 11; port++)
                {
                    RF1356.RFReaderOpen(port);

                    reply = RF1356.BaudDetec(port);

                    if (reply == RF1356.REPLY.RF_OK)
                    {
                        PortNO = port;
                        //MessageBox.Show("성공");
                        break;
                    }
                }

                if (reply != RF1356.REPLY.RF_OK)
                    MessageBox.Show("COM Port Open Fail", "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }



            int tagCnt = 0;
            string SerialNumbers = String.Empty;
            string UID = String.Empty;       //이 부분에서 UID를 입력해 주는 것이 필요함


            reply = RF1356.RFReadSerialNO(PortNO, ref SerialNumbers);//9


            switch (reply)
            {
                case RF1356.REPLY.RF_OK:
                    tagCnt = int.Parse(SerialNumbers.Substring(0, 2));

                    for (int i = 0; i < tagCnt; i++)
                    {
                        string str = SerialNumbers.Substring(2 + (16 * i), 16);//9
                                                                               //string UID = String.Empty;


                        for (int j = 0; j < 8; j++)
                        {
                            UID = str.Substring(2 * j, 2) + UID;//9
                        }

                    }

                    //MessageBox.Show(UID);

                    txtCardId.Text = UID;
                    break;

                case RF1356.REPLY.NO_TRANSPONDER:
                    MessageBox.Show("연결 안 됨");
                    break;

                case RF1356.REPLY.RF_ERR:
                    MessageBox.Show("오류");
                    break;

                default:
                    break;
            }

            if (txtCardId.Text == "")
            {
                MessageBox.Show("Select Tag UID", "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }
        }

        public static RF1356.REPLY reply; // 리턴 상태를 반환하는 변수
        public static long PortNO;        // 시리얼 포트 번호 


        private void btnCancel_Click(object sender, EventArgs e)
        {

            try
            {
                if (RF1356.RFReaderClose(PortNO))
                {
                    try
                    {
                        if (RF1356.RFReaderIsOpen(PortNO))
                            RF1356.RFReaderClose(PortNO);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            this.Close();
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {

            MessageBox.Show(cboEmployeeNo.SelectedItem.ToString());
            if (txtCardId.Text == "")
            {
                MessageBox.Show("Select Tag UID", "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }


            string UID = txtCardId.Text;       //이 부분에서 UID를 입력해 주는 것이 필요함
            string DataBlocks = String.Empty;
            string Data = String.Empty;

            DataBlocks = RF1356.str2hex(cboEmployeeNo.SelectedItem.ToString());

            reply = RF1356.RFWriteDataBlock(PortNO, UID, ref DataBlocks, 0, 1);

            var p = context.Cards.Where(c => c.CaNo == UID).Select(c => c.CaNo);

            if (p.Count() > 0)
            {
                MessageBox.Show("이미 등록 된 카드 입니다.");                
            }
            else
            {
                switch (reply)
                {
                    case RF1356.REPLY.RF_OK:
                        MessageBox.Show("Write Success", "OK",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Asterisk,
                                    MessageBoxDefaultButton.Button1);
                        break;

                    case RF1356.REPLY.NO_TRANSPONDER:
                        MessageBox.Show("연결 안 됨");
                        break;

                    case RF1356.REPLY.RF_ERR:
                        MessageBox.Show("실패");
                        break;

                    case RF1356.REPLY.INVALID_PARAMETER:
                        MessageBox.Show("값을 넣어주세요");
                        break;

                    default:
                        break;
                }



                DialogResult dialogResult = MessageBox.Show("등록하시겠습니까?", "카드 등록", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    Card card = new Card
                    {
                        CaNo = txtCardId.Text.Trim(),
                        EmNo = int.Parse(cboEmployeeNo.SelectedItem.ToString()),
                        CDate = DateTime.Now,
                        Active = true
                    };
                    dm.CardAdd(card);

                    try
                    {
                        if (RF1356.RFReaderClose(PortNO))
                        {
                            try
                            {
                                if (RF1356.RFReaderIsOpen(PortNO))
                                    RF1356.RFReaderClose(PortNO);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                    this.Close();
                }
                else if (dialogResult == DialogResult.No)
                {
                    try
                    {
                        if (RF1356.RFReaderClose(PortNO))
                        {
                            try
                            {
                                if (RF1356.RFReaderIsOpen(PortNO))
                                    RF1356.RFReaderClose(PortNO);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                    this.Close();
                }
            }
        }
    }
}
